import React, { useState, useEffect } from 'react';
import { Result, Button } from 'antd';
import { history } from 'umi';

interface PermissionWrapperProps {
  children: React.ReactNode;
  permission?: string;
  fallback?: React.ReactNode;
}

const PermissionWrapper: React.FC<PermissionWrapperProps> = ({
  children,
  permission,
  fallback,
}) => {
  const [userPermissions, setUserPermissions] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchPermissions = async () => {
      try {
        const response = await fetch('/api/auth/permissions', {
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`,
          },
        });
        if (response.ok) {
          const permissions = await response.json();
          setUserPermissions(permissions || []);
        }
      } catch (error) {
        console.error('获取权限失败:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchPermissions();
  }, []);

  if (loading) {
    return <div>加载中...</div>;
  }

  if (permission && !userPermissions.includes(permission)) {
    if (fallback) {
      return <>{fallback}</>;
    }
    
    return (
      <Result
        status="403"
        title="403"
        subTitle="抱歉，您没有权限访问此页面"
        extra={
          <Button type="primary" onClick={() => history.push('/dashboard')}>
            返回首页
          </Button>
        }
      />
    );
  }

  return <>{children}</>;
};

export default PermissionWrapper;